'''
Description: 
Project: 
Author: michelle
Date: 2022-03-18 14:55:45
LastEditors: michelle
LastEditTime: 2022-03-18 15:23:07
Modified By: michelle
FilePath: /docke-fast-demo/main.py
'''

from fastapi import FastAPI,HTTPException
from fastapi.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise,HTTPNotFoundError
from models.users import Users,UserIn_Pydantic,User_Pydantic
import uvicorn
from typing import List
from pydantic import BaseModel

app = FastAPI(title='docker-fast-demo')

# 跨域设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=('*'),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 连接数据库
register_tortoise(
    app,
    # 按照下面格式换成指定数据库访问链接
    db_url='mysql://{user}:{pwd}@127.0.0.1:3306/{dbname}',
    modules={"models": ["models.users"]},
    generate_schemas=True, #如果数据库为空，则自动生成对应表单,生产环境不要开
    add_exception_handlers=True, #生产环境不要开，会泄露调试信息
)

class Status(BaseModel):
    message: str


@app.get("/users", response_model=List[User_Pydantic])
async def get_users():
    return await User_Pydantic.from_queryset(Users.all())


@app.post("/users", response_model=User_Pydantic)
async def create_user(user: UserIn_Pydantic):
    user_obj = await Users.create(**user.dict(exclude_unset=True))
    return await User_Pydantic.from_tortoise_orm(user_obj)


@app.get(
    "/user/{user_id}", response_model=User_Pydantic, responses={404: {"model": HTTPNotFoundError}}
)
async def get_user(user_id: int):
    return await User_Pydantic.from_queryset_single(Users.get(id=user_id))


@app.put(
    "/user/{user_id}", response_model=User_Pydantic, responses={404: {"model": HTTPNotFoundError}}
)
async def update_user(user_id: int, user: UserIn_Pydantic):
    await Users.filter(id=user_id).update(**user.dict(exclude_unset=True))
    return await User_Pydantic.from_queryset_single(Users.get(id=user_id))


@app.delete("/user/{user_id}", response_model=Status, responses={404: {"model": HTTPNotFoundError}})
async def delete_user(user_id: int):
    deleted_count = await Users.filter(id=user_id).delete()
    if not deleted_count:
        raise HTTPException(status_code=404, detail=f"User {user_id} not found")
    return Status(message=f"Deleted user {user_id}")


# 启动
if __name__ == "__main__":
    uvicorn.run(
        app="main:app", 
        host='0.0.0.0', 
        port=8002,
        reload=True
    )
